package com.atguigu.gulimall.member.service.impl;

import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberUserRegisterVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberUserRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();

        // 默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        // 检查用户名和手机是否一致
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setNickname(vo.getUserName());

        // 设置密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(password);

        // 其他默认信息

        this.baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
        throw new UsernameExistException();
        }
    }

    /**
     * 本地登录（非第三方登录）实现逻辑
     * @param vo 用户信息
     * @return 用户的所有信息
     */
    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        // 去数据库查询
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        if (memberEntity == null || !passwordEncoder.matches(password, memberEntity.getPassword())) {
            return null;
        }
        return memberEntity;
    }

    /**
     * 结合数据库判断用户的登录情况
     * @param socialUser 用户第三方账号信息
     * @return 用户完整信息
     */
    @Override
    public MemberEntity login(SocialUser socialUser) {
        // 登陆注册合并逻辑
        Long uid = socialUser.getId();
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            // 注册过
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getResponseEntity().getAccess_token());
            update.setExpiresIn(socialUser.getResponseEntity().getExpires_in());

            this.baseMapper.updateById(update);

            memberEntity.setAccessToken(socialUser.getResponseEntity().getAccess_token());
            memberEntity.setExpiresIn(socialUser.getResponseEntity().getExpires_in());

            return memberEntity;
        } else {
            // 还没有注册过
            MemberEntity register = new MemberEntity();
            register.setNickname(socialUser.getName());
            register.setGender(1);
            register.setHeader(socialUser.getAvatar_url());
            register.setCreateTime(new Date());
            register.setSocialUid(uid.toString());
            register.setAccessToken(socialUser.getResponseEntity().getAccess_token());
            register.setExpiresIn(socialUser.getResponseEntity().getExpires_in());

            this.baseMapper.insert(register);

            return register;
        }
    }
}